/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.st.service;

import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.st.config.Constant;
import com.jeesite.modules.st.dao.StProductMaterialFormBillDao;
import com.jeesite.modules.st.dao.StProductMaterialFormBillDetailDao;
import com.jeesite.modules.st.entity.*;
import com.jeesite.modules.st.utils.BillUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 生产领料Service
 *
 * @author HOHD
 * @version 2020-12-22
 */
@Service
@Transactional(readOnly = true)
public class StProductMaterialFormBillService extends CrudService<StProductMaterialFormBillDao, StProductMaterialFormBill> {

    @Autowired
    private StProductMaterialFormBillDetailDao stProductMaterialFormBillDetailDao;

    /**
     * 获取单条数据
     *
     * @param stProductMaterialFormBill
     * @return
     */
    @Override
    public StProductMaterialFormBill get(StProductMaterialFormBill stProductMaterialFormBill) {
        StProductMaterialFormBill entity = super.get(stProductMaterialFormBill);
        if (entity != null) {
            StProductMaterialFormBillDetail stProductMaterialFormBillDetail = new StProductMaterialFormBillDetail(entity);
            stProductMaterialFormBillDetail.setStatus(StProductMaterialFormBillDetail.STATUS_NORMAL);
            entity.setStProductMaterialFormBillDetailList(stProductMaterialFormBillDetailDao.findList(stProductMaterialFormBillDetail));
        }
        return entity;
    }

    /**
     * 查询分页数据
     *
     * @param stProductMaterialFormBill 查询条件
     * @return
     */
    @Override
    public Page<StProductMaterialFormBill> findPage(StProductMaterialFormBill stProductMaterialFormBill) {
        return super.findPage(stProductMaterialFormBill);
    }

    @Autowired
    StSmallMaterialApproveService stSmallMaterialApproveService;

    @Autowired
    StMaterialRecordService stMaterialRecordService;

    @Autowired
    StProductBillService stProductBillService;
    @Autowired
    StWarehouseInventoryService stWarehouseInventoryService;
    @Resource
    BillUtil billUtil;

    /**
     * 生成实时库存记录
     *
     * @param stProductMaterialFormBillDetail
     * @param billNo
     */
    private void saveWarehouseInventory(StProductMaterialFormBillDetail stProductMaterialFormBillDetail, String billNo) {
        String id = stProductMaterialFormBillDetail.getId();

        String batchNumber = stProductMaterialFormBillDetail.getBatchNumber();
        String[] bArr = batchNumber.split(",");
        for (String batchN : bArr) {
            if (StringUtils.isEmpty(batchN)) {
                continue;
            }
            String warehouseId = batchN.split("_")[0];
            String batch = batchN.split("_")[1];
            String num = batchN.split("_")[2];
            String materialName = stProductMaterialFormBillDetail.getMaterialName();
            StMaterialRecord stMaterialRecord = stMaterialRecordService.get(materialName);
            StWarehouseInventory warehouseInventory = new StWarehouseInventory();
            warehouseInventory.setMaterialCode(stMaterialRecord.getMaterialCode());
            warehouseInventory.setBatchNumber(batch);
//            List<StWarehouseInventory> list = stWarehouseInventoryDao.findList(warehouseInventory);
//            StWarehouseInventory stTemp = list.get(0);

            warehouseInventory.setPrimaryDetailId(id);
            warehouseInventory.setNumber(new BigDecimal(num));
            warehouseInventory.setBillCategory(BillUtil.BillType.productMaterialBill.getBillCode());//种类
//            int inOrOut = BillJudge.judgeInOrOut(billType);
            warehouseInventory.setInOrOut(Constant.in_or_out.out);
            warehouseInventory.setBillNo(billNo);
            warehouseInventory.setWarehouse(warehouseId);
            stWarehouseInventoryService.save(warehouseInventory);
        }
    }

    // 新增和删除是成对的
    private void removeWarehouseLog(String id) {
        StWarehouseInventory stNull = new StWarehouseInventory();
        stNull.setPrimaryDetailId(id);
//            stNull.setBillNo(stInventoryBillDetail.getBillNo());
        List<StWarehouseInventory> list = stWarehouseInventoryService.findList(stNull);
        for (StWarehouseInventory warehouseInventory : list) {
            stWarehouseInventoryService.delete(warehouseInventory);
        }
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param stProductMaterialFormBill
     */
    @Override
    @Transactional(readOnly = false)
    public void save(StProductMaterialFormBill stProductMaterialFormBill) {
        Integer primeApproveState = 2;
        if (stProductMaterialFormBill.getIsNewRecord()) {
            String billNo = billUtil.billNo(BillUtil.BillType.productMaterialBill);
            stProductMaterialFormBill.setBillNo(billNo);
        } else
            primeApproveState = get(stProductMaterialFormBill.getId()).getApproveState();
        Integer change = stProductMaterialFormBill.getApproveState();
        if (change == null) change = 2;
        if (2 == primeApproveState && change == 4) {//已审核状态
            String productBillIds = stProductMaterialFormBill.getProductBillIds();
            stProductBillService.setBillStatus(productBillIds);
            for (StProductMaterialFormBillDetail stProductMaterialFormBillDetail : stProductMaterialFormBill.getStProductMaterialFormBillDetailList()) {
                saveWarehouseInventory(stProductMaterialFormBillDetail, stProductMaterialFormBill.getBillNo());
            }
        }
        if (4 == primeApproveState && change == 2) {//弃审
            for (StProductMaterialFormBillDetail stProductMaterialFormBillDetail : stProductMaterialFormBill.getStProductMaterialFormBillDetailList()) {
                removeWarehouseLog(stProductMaterialFormBillDetail.getId());
            }
        }
        super.save(stProductMaterialFormBill);
        // 保存 StProductMaterialFormBill子表
        for (StProductMaterialFormBillDetail stProductMaterialFormBillDetail : stProductMaterialFormBill.getStProductMaterialFormBillDetailList()) {
            if (!StProductMaterialFormBillDetail.STATUS_DELETE.equals(stProductMaterialFormBillDetail.getStatus())) {
                stProductMaterialFormBillDetail.setParentId(stProductMaterialFormBill);
                if (stProductMaterialFormBillDetail.getIsNewRecord()) {
                    stProductMaterialFormBillDetailDao.insert(stProductMaterialFormBillDetail);
                } else {
                    stProductMaterialFormBillDetailDao.update(stProductMaterialFormBillDetail);

                    if (2 == primeApproveState && change == 4) {//已审核状态
                        do {
                            String materialName = stProductMaterialFormBillDetail.getMaterialName();
                            StSmallMaterialApprove stSmallMaterialApprove = new StSmallMaterialApprove();
                            StMaterialRecord stMaterialRecord = stMaterialRecordService.get(materialName);
                            if (Constant.st_material_category.small != stMaterialRecord.getMaterialCategory()) {
                                //不是小料不行
                                break;
                            }
                            String materialCode = stMaterialRecord.getMaterialCode();
                            String materialTrueName = stMaterialRecord.getMaterialName();
                            stSmallMaterialApprove.setMaterialCode(materialCode);
                            List<StSmallMaterialApprove> list = stSmallMaterialApproveService.findList(stSmallMaterialApprove);
                            if (list.size() > 1) throw new IllegalArgumentException("只能有一个");

                            int getNumber = stProductMaterialFormBillDetail.getGetNumber();
                            int caseNumber = stProductMaterialFormBillDetail.getCaseNumber();
                            BigDecimal theoryNumber = stProductMaterialFormBillDetail.getTheoryNumber();
                            BigDecimal theoryLeft = stProductMaterialFormBillDetail.getTheoryLeft();
                            BigDecimal theoryNumberBD = theoryNumber;
                            BigDecimal theoryLeftBD = theoryLeft;
                            BigDecimal onlineNumber = new BigDecimal("0");
                            BigDecimal takeStockValue = new BigDecimal("0");
                            if (list.isEmpty()) {
                                //没有就new
                                stSmallMaterialApprove = new StSmallMaterialApprove();
                            } else {
                                stSmallMaterialApprove = list.get(0);
                                Integer getNumberDb = stSmallMaterialApprove.getGetNumber();
                                Integer caseNumberDb = stSmallMaterialApprove.getCaseNumber();
                                BigDecimal theoryUseNumber = stSmallMaterialApprove.getTheoryUseNumber();
                                onlineNumber = stSmallMaterialApprove.getOnlineNumber();
                                takeStockValue = stSmallMaterialApprove.getTakeStockValue();
                                theoryNumberBD = theoryNumberBD.add(theoryUseNumber);
                                getNumber += getNumberDb;
                                caseNumber += caseNumberDb;
                            }
                            BigDecimal theoryLeftNumber = onlineNumber
                                    .add(new BigDecimal(getNumber + "")).subtract(theoryNumberBD);
                            stSmallMaterialApprove.setTheoryLeftNumber(theoryLeftNumber);
                            stSmallMaterialApprove.setGetNumber(getNumber);
                            stSmallMaterialApprove.setCaseNumber(caseNumber);
                            stSmallMaterialApprove.setTheoryUseNumber(theoryNumberBD);
                            stSmallMaterialApprove.setMaterialCode(materialCode);
                            stSmallMaterialApprove.setMaterialName(materialTrueName);
//                        stSmallMaterialApprove.setTheoryLeftNumber(theoryLeftBD);
                            BigDecimal diffNumber = takeStockValue.subtract(theoryLeftNumber);
                            stSmallMaterialApprove.setDiffNumber(diffNumber);

                            BigDecimal profitLossPercent;
                            if (caseNumber != 0) {
                                profitLossPercent = diffNumber.divide(new BigDecimal(caseNumber + ""), 2, BigDecimal.ROUND_HALF_DOWN);
                            } else {
                                profitLossPercent = new BigDecimal("0");
                            }
                            stSmallMaterialApprove.setProfitLossPercent(profitLossPercent);

                            stSmallMaterialApproveService.save(stSmallMaterialApprove);
                        } while (false);
                    }
                }
            } else {
                stProductMaterialFormBillDetailDao.delete(stProductMaterialFormBillDetail);
            }
        }
    }

    /**
     * 更新状态
     *
     * @param stProductMaterialFormBill
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatus(StProductMaterialFormBill stProductMaterialFormBill) {
        super.updateStatus(stProductMaterialFormBill);
    }

    /**
     * 删除数据
     *
     * @param stProductMaterialFormBill
     */
    @Override
    @Transactional(readOnly = false)
    public void delete(StProductMaterialFormBill stProductMaterialFormBill) {
        super.delete(stProductMaterialFormBill);
        StProductMaterialFormBillDetail stProductMaterialFormBillDetail = new StProductMaterialFormBillDetail();
        stProductMaterialFormBillDetail.setParentId(stProductMaterialFormBill);
        stProductMaterialFormBillDetailDao.deleteByEntity(stProductMaterialFormBillDetail);
    }

}